package com.example.webdriveddd.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
@Configuration
public class SecurityConfig {
    @Autowired
    private MyUserService myUserService;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity.userDetailsService(myUserService)
                .formLogin(config->{
                    config.loginProcessingUrl("/doLogin")
                            .loginPage("/login.html")
                            .usernameParameter("username")
                            .passwordParameter("password")
                            .permitAll();
                })
                .logout(Customizer.withDefaults())
                .csrf(AbstractHttpConfigurer::disable)
                .cors(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(config->{
                    config.requestMatchers("/doLogin").permitAll()
                            .requestMatchers("/register").permitAll()
                            .requestMatchers("/register.html").permitAll()
                            .requestMatchers("/share").permitAll()
                            .requestMatchers("/share/verify").permitAll()
                            .requestMatchers("/sharePage").permitAll()
                            .requestMatchers("/img/**").permitAll()
                            .anyRequest().authenticated();
                })
                .build();
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
